<template>
	<view class="ca">
		<camera device-position="front" flash="off" binderror="error" :style="{height: phoneheigtht+'px'}"></camera>
		<view class="text">
			请拍照上传人脸信息
		</view>
		<view class="facebutton" type="primary" @click="getPhoto">
			<uni-icons size="40" type="camera"></uni-icons>
		</view>
	</view>
</template>

<script>
	import {
		mapState
	} from 'vuex'
	export default {
		data() {
			return {
				src: "", //图片的链接
				base64: "",
				msg: "",
				// 设备窗口高度
				phoneheigtht: 0,
			};
		},
		onLoad() {
			const sysInfo = uni.getSystemInfoSync()
			this.phoneheigtht = sysInfo.windowHeight
		},
		computed: {
			//将m_user模块中的userinfo映射到当前页面
			...mapState('m_user', ['userinfo'])
		},
		methods: {
			getPhoto() {
				var that = this;
				const ctx = wx.createCameraContext()
				ctx.takePhoto({
					quality: 'high',
					success: (res) => {
						that.src = res.tempImagePath
						//将获取的图片转码为base64
						wx.getFileSystemManager().readFile({
							filePath: that.src, //图片返回路径
							encoding: 'base64', //格式
							success: (res) => {
								that.base64 = res.data
								this.add()
							}
						})
					} //拍照结束
				}) //调用相机结束
			},


			add() {
				wx.request({
						url: 'http://81.68.103.193:3000/api/faceregister',
						method: 'POST',
						data: {
							image: this.base64,
							_id: this.userinfo._id,
						},
						success(res) {
							console.log(res)
							if (res.data.meta.status == 200) {
								wx.showToast({
									title: '人脸上传成功',
									icon: "success",
									duration: 2500,
								})
								setTimeout(function() {
									wx.navigateBack()
								}, 1500)

							} else {
								wx.showToast({
									title: '请重试',
									icon: "error",
									duration: 2500,
								})
							}
						}
					}),
					//失败尝试
					wx.showToast({
						title: '加载中',
						icon: 'loading',
						duration: 1000
					})
			}
		}

	}
</script>

<style lang="scss">
	.ca {
		display: flex;
		justify-content: center;

		.facebutton {
			position: fixed;
			display: flex;
			align-items: center;
			justify-content: center;
			width: 60px;
			height: 60px;
			border-radius: 50%;
			bottom: 50px;
			background: rgba($color: #ffffff, $alpha: 0.6);

			&:active {
				background: rgba($color: #ffffff, $alpha: 0.2);
			}
		}

		.text {
			position: fixed;
			top: 70px;
			font-size: 18px;
			color: #FFFFFF;
		}
	}
</style>
